/**
 * Created by udi on 2016/9/16.
 */
'use strict'

//Map.prototype.add = function (json) {
//    if (!json) return this;

//    if (json instanceof Map) {
//        for (let kv of json) {
//            this.set(kv[0], kv[1]);
//        }
//    }

//    for (let k in json) {
//        this.set(k, json[k]);
//    }
//    return this;
//}
String.prototype.mySplit = function (reg, arg) {
  return this.split(reg, arg).filter(o => o);
}

String.prototype.escapeRegExp = function () {
  return this.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}

//查找最近的一个字符串索引。
String.prototype.findFirstIndex = function (startIndex, match) {
  for (let i = startIndex; i < this.length; i++) {
    if (match(this[i])) return i;
  }
  return -1;
}

//特殊字符
String.specialString = "`~!@#$%^&*()_+{}|:\"<>?-=[]\\;',./\t\n";


let jv = new Object();

//简单判断一个对象是否为空 严格意义上的null ， false,0 不算空.
jv.isNull = function (obj) {
  if (typeof (obj) === "undefined") return true;

  if (obj === null) return true;
  // //既然能传递到这里，那说明一定是有意义的。
  // if (obj === undefined) return true;
  return false;
}

//转为数值型
jv.getInt = function (Value) {
  ///<summary>转为数值型</summary>
  if (!Value) return 0;

  var ret = parseInt(Value);
  if (ret === 0) return ret;

  return ret || 0;
}

//判断是否在一个区间，包含等于
jv.between = function (val, from, to) {
  return (val >= from) && (val <= to);
}

//首字母大写
jv.translateDbName = function (name, firstLetterCap) {
  if (!name) return "";
  return name.mySplit(" _+-&|:;<>,.$(){}").map(o => o.slice(0, 1).toUpperCase() + o.slice(1).toLowerCase()).join("");
}

//时间的随机码
jv.randomCode = function (length) {
  let rs = Math.random().toString(36).slice(3).replace("0", "").replace("o", "").replace("z", "").replace("2", "");

  if( jv.isNull(length)){
    return rs;
  }

  let str = rs.slice(0, length);
  if (str.length < length) {
    str += jv.randomCode(length - str.length);
  }
  return str;
}

//扩展对象，并返回。
jv.extend = function () {
  if (!arguments.length)return null;

  var result = arguments[0];

  for (var i = 1; i < arguments.length; i++) {
    var toMerge = arguments[i];


    for (var k in toMerge) {
      let v = toMerge[k];
      if (v === null) continue;
      if (!v && typeof(v) == "undefined") continue;

      result[k] = toMerge[k];
    }
  }
  return result;
}

//收缩对象并返回
jv.retain = function (json) {
  if (arguments.length < 2) return json;

  let retJson = {};
  for (var i = 1; i < arguments.length; i++) {
    var key = arguments[i];
    var v = json[key];
    if (v === null) continue;
    if (!v && typeof(v) == "undefined") continue;

    retJson[key] = v;
  }
  return retJson;
}

jv.post = async(opt) => {
  return new Promise(function (resolve, reject) {
    opt.headers = jv.extend({"Content-Type": "application/json"}, opt.headers);

    return require('request')(jv.extend({
        method: 'POST',
        preambleCRLF: true,
        postambleCRLF: true,
        body: {},
        json: true,
        uri: "" // uri or url
      }, opt),
      function (error, response, body) {
        if (error) {
          return reject(error);
        }

        return resolve(response);
      });
  });
}

jv.defineProperty = function (target, functionName, func, isEnumerable) {

  try {
    if (Object.defineProperty) {
      Object.defineProperty(target, functionName, {value: func, enumerable: isEnumerable || false});
    }
    else {
      target[functionName] = func;
    }
  }
  catch (e) {
    target[functionName] = func;
  }
}

jv.defineProperty(String.prototype, 'padLeft', function (Length, Char) {
  var addtional = "";
  for (var i = 0, len = Length - this.length; i < len; i++) {
    addtional += Char;
  }
  return addtional + this;
});


jv.defineProperty(String.prototype, 'padRight', function (Length, Char) {
  var addtional = "";
  for (var i = 0, len = Length - this.length; i < len; i++) {
    addtional += Char;
  }
  return this + addtional;
});


//保持和C#同样的格式。yyyyMMdd HHmmss
jv.defineProperty(Date.prototype, 'toString', function () {
  var arg = arguments[0], format = arg;
  if (!format) format = "yyyy-MM-dd";

  var y = this.getFullYear(), m = this.getMonth(), d = this.getDate(), h = this.getHours(), mi = this.getMinutes(), s = this.getSeconds();
  if (y == 1 || (y <= 1901)) return "";

  if (!arg) {
    if (h > 0 || mi > 0 || s > 0) {
      format += " HH:mm";

      if (s > 0) {
        format += ":ss";
      }
    }
  }


  return format.replace(new RegExp("yyyy", "g"), y)
    .replace(new RegExp("MM", "g"), (m + 1).toString().padLeft(2, "0"))
    .replace(new RegExp("dd", "g"), d.toString().padLeft(2, "0"))
    .replace(new RegExp("HH", "g"), h.toString().padLeft(2, "0"))
    .replace(new RegExp("mm", "g"), mi.toString().padLeft(2, "0"))
    .replace(new RegExp("ss", "g"), s.toString().padLeft(2, "0"))
    .replace(new RegExp("yy", "g"), y.toString().slice(2))
    .replace(new RegExp("M", "g"), m + 1)
    .replace(new RegExp("d", "g"), d)
    .replace(new RegExp("hh", "g"), h)
    .replace(new RegExp("m", "g"), mi)
    .replace(new RegExp("s", "g"), s);

});


jv.log = console.log;
jv.error = jv.log;

//Object.assign(exports, jv);
exports.jv = jv;

